/*
 * connexion.c
 * projet Unix: 6 qui prend
 *
 *  @authors Doublier Sami
 *  @authors Pingot Alexandre
 */

#include "connexion.h"

int createSocket() {
	int sck; /* descripteur */
	SYS(sck=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); /* création d'un socket */
	return sck;
}

struct hostent * initHost(char * hostName) {
	struct hostent * host;
	host = gethostbyname(hostName);
	if (host == NULL) {
		fprintf(stderr,"L'hôte est introuvable.\n");
		exit(1);
	}
	return host;
}

struct sockaddr_in * initClientAddress(int port, struct hostent * host) {
	struct sockaddr_in * serv_addr = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in));
	bzero((char*) serv_addr, sizeof(struct sockaddr_in));
	serv_addr->sin_family = AF_INET;
	serv_addr->sin_port = htons(port);

	/* Copie de l'adresse du serveur dans la structure sockaddr_in */
	bcopy(host->h_addr, (char*) &(serv_addr->sin_addr.s_addr), host->h_length);
	return serv_addr;
}

void startConnection(int scket, struct sockaddr_in * address) {
	if (connect(scket, (struct sockaddr *) address, sizeof(struct sockaddr_in)) < 0) {
		fprintf(stderr,"Echec lors de la connexion\n");
		SYS(close(scket));
		exit(1);
	}
}

int verifierNumPort(char * chaine) {
	int val;
	val = atoi(chaine);
	if(val<=1024){
		return 1;
	}
	return 0;
}

void closeConnectionClient(int socketclient ,message * msg){
	SYSS(write(socketclient, msg, sizeof(message)));
	SYSS(close(socketclient));
}
